package com.ibiz.znjd.znjd;

import android.app.Notification;

import com.ibiz.znjd.MainActivity;
import com.ibiz.znjd.MainApplication;
import com.ibiz.znjd.baidu.location.NotificationUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 报到计划工具类
 */
public class RecordPlanUtil {

    /**
     * 设置默认通知提前量为30分钟
     */
    static int beforeTime = 30;

    /**
     * 上次初始化时间
     */
    static long lastInitTime = 0;

    /**
     * 报到集合
     */
    static JSONArray recordArr;

    /**
     * 报到请求路径
     */
    static String recordUrl = "";

    /**
     * 初始化提前间隔量和报到数据。
     * @param mainActivity
     */
    public static void init(MainActivity mainActivity){
        // 根据配置设置通知提前间隔
        Map<String,String> envMap = ((MainApplication)(mainActivity.getApplication())).envMap;
        try {
            if(null != envMap.get("bdsjBefore")){
                beforeTime = Integer.parseInt(envMap.get("bdsjBefore"));
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        // 拉取报到数据
        String recordUrl = envMap.get("recordUrl");
        String token = envMap.get("token");
        String personid = envMap.get("personid");
        if(recordUrl == null || token == null || personid == null){
            return;
        }
        recordUrl = recordUrl.replace("${persionid}",personid);


        // 当前时间
        Date date = new Date();
        String strDateFormat = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        String time = sdf.format(date);

        // 发起请求
        OkHttpClient client = new OkHttpClient();
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        JSONObject json = new JSONObject();
        try {
            json.put("sort", "jgbdsj,asc");
            json.put("n_jgbdsj_gtandeq", time);
        }catch (Exception e){
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(JSON,json.toString());
        Request request = new Request.Builder()
                .header("Authorization", "Bearer " + token)
                .header("deviceType", "app")
                .url(recordUrl)
                .post(body)
                .build();
        Call call = client.newCall(request);

        System.out.println("报到数据请求参数："+json.toString());
        System.out.println("报到数据请求url："+recordUrl);
        System.out.println("报到数据请求token："+token);

        // 请求回调
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("报到数据获取失败！");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                if(response.isSuccessful()){
                    //处理UI需要切换到UI线程处理
                    System.out.println("报到数据获取成功："+result);
                    lastInitTime = new Date().getTime();
                    try {
                        JSONObject resultJson = new JSONObject(result);
                        JSONArray content = resultJson.getJSONArray("content");
                        JSONArray records = new JSONArray();
                        if(null != content && content.length() > 0){
                            // 日期格式化
                            String strDateFormat = "yyyy-MM-dd HH:mm:ss";
                            SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
                            for (int i = 0; i < content.length(); i++) {
                                JSONObject record = new JSONObject();
                                String timeStr = content.getJSONObject(i).getString("jgbdsj");
                                // 计算提前量的时间
                                Calendar calendar = Calendar.getInstance();
                                calendar.setTime(sdf.parse(timeStr));
                                calendar.add(Calendar.MINUTE, -1 * beforeTime);
                                record.put("notifyTime", calendar.getTime().getTime());
                                record.put("notifyText", "请于"+timeStr+"报到");
                                records.put(i,record);
                            }
                            recordArr = records;
                        }

                    } catch (JSONException | ParseException e) {
                        e.printStackTrace();
                    }
                }else{
                    System.out.println("报到数据获取失败："+result);
                }
                System.out.println(result);
            }
        });
    }

    /**
     * 检测是否需要通知
     * @param mainActivity
     */
    public static void test(MainActivity mainActivity){
        long current = new Date().getTime();
        // 超过6小时重新拉一遍报到数据
        if((current - lastInitTime) > 1000 * 60 * 60 * 6){
            RecordPlanUtil.init(mainActivity);
            return;
        }
        if(null != recordArr && recordArr.length() > 0){
            try {
                if(current > recordArr.getJSONObject(0).getLong("notifyTime")){
                    notify("报到提醒",recordArr.getJSONObject(0).getString("notifyText"), mainActivity );
                    recordArr.remove(0);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 发送报到提醒通知
     * @param title 标题
     * @param message 内容
     */
    public static void notify(String title, String message, MainActivity mainActivity){
        NotificationUtils notificationUtils = mainActivity.notificationUtils;
        Notification.Builder builder = notificationUtils.getAndroidChannelNotification(title,message);
        notificationUtils.showNotification(builder.build());
    }
}
